package com.boe.csb.core.common.generator;

/**
 * Created by edz on 16/11/20.
 */

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.lang.reflect.Method;


public class CriteriaGenerator<T, E> {

    private Logger logger = LoggerFactory.getLogger(CriteriaGenerator.class);

    public void generate(T criteria, E obj) {
        try {
            Method method = criteria.getClass().getDeclaredMethod("createCriteria", null);

            Object subCriteria = method.invoke(criteria, null);

            generateInner(subCriteria, obj);

        } catch (Exception e) {
            logger.error("生成creiteria出错", e);
        }

    }

    public void generateInner(Object subCriteria, E obj) {
        Field[] fields = obj.getClass().getSuperclass().getDeclaredFields();
        try {
            Method method = null;

            for (Field field : fields) {
                field.setAccessible(true);
                String fieldName = field.getName();
                if (fieldName.equalsIgnoreCase("SerialVersionUID")) {
                    continue;
                }
                if (field.get(obj) != null) {
                    method = subCriteria.getClass().getDeclaredMethod(getSetMethodName(fieldName), field.getType());
                    method.invoke(subCriteria, field.get(obj));
                }

            }
        } catch (Exception e) {
            logger.error("生成creiteria出错", e);
        }
    }


    private String getSetMethodName(String fieldName) {
        return String.format("and%sEqualTo", fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1));
    }

}
